// src/router.js

import { createRouter, createWebHistory } from 'vue-router'
import LoginView from './views/LoginView.vue'
import RegisterView from './views/RegisterView.vue'
import BlogIndex from './views/BlogIndex.vue'
import NewPost from './views/NewPost.vue'
import BlogDetailView from './views/BlogDetailView.vue'
 
const routes = [
  { path: '/login', component: LoginView },
  { path: '/register', component: RegisterView },
  { path: '/index', component: BlogIndex },
  { path: '/new-post', component: NewPost, meta: { requiresAuth: true } },
  {
    path: '/post/:id',
    component: BlogDetailView,
    name: 'BlogDetail'
  },
  // 👇 添加以下通配符路由
  {
    path: '/:pathMatch(.*)*',
    redirect: '/index'
  }
]

const router = createRouter({
  history: createWebHistory(),
  routes
})
//   添加全局前置守卫
router.beforeEach((to, from, next) => {
  const requiresAuth = to.matched.some(record => record.meta.requiresAuth);
  const token = localStorage.getItem('token');

  if (requiresAuth && !token) {
    // 如果目标页面需要登录且没有 token，则跳转到 index
    next('/index');
  } else {
    next();
  }
});

export default router